﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FatHunter_InHouse : Hunter_InHouse
{

    [SerializeField] private float rushSpeed;
    [SerializeField] private float maxDistance;
    [SerializeField] private LayerMask layerMask;
    [SerializeField] private Transform catch_Point;

    private float minDistance = 2f;

    bool isfind;

    private void Rush(Transform target)
    {
        Walk(target.position, rushSpeed);
    }

    public override void Attack(Transform player)
    {
        isfind = SetRay(player.position);

        //Debug.Log(isfind);

        if (!isfind)
        {
            StopAttack();
            Invoke("StartPatrol", 1f);
            return;
        }
            

        Rush(player);
        float distance = Vector2.Distance(transform.position, player.position);
        if ( distance >= maxDistance)
        {
            StopAttack();
            Invoke("StartPatrol", 1f);
        }
        else if (distance < minDistance)
        {
            base.Attack(player);
            StopMove();

            float size = Vector2.Distance(player.position, transform.position);
            Vector3 mid = new Vector3((player.position.x + transform.position.x) / 2, (player.position.y + transform.position.y) / 2, 0);

            EventManager.Invoke(EventNameConfig.GanmeEnd.PlayerInEndLight, mid, (size + 2f) / 2);
        }
             
    }

    bool SetRay(Vector2 target)
    {
        Vector2 direction = new Vector2(target.x - transform.position.x, target.y - transform.position.y);
        Ray2D ray = new Ray2D(transform.position, direction);
        //Debug.Log(transform.position + " " + direction) ;
        Debug.DrawRay(ray.origin, direction, Color.green, 0.2f);

        RaycastHit2D rayInfo = Physics2D.Raycast(ray.origin, ray.direction, Vector2.Distance(target, transform.position), layerMask);

        //RaycastHit2D rayInfo = Physics2D.Linecast(ray.origin, ray.direction,layerMask);

        if (rayInfo.collider != null)
        {
            //Debug.Log(rayInfo.collider+" "+rayInfo.distance);
            if (rayInfo.collider.tag.Equals(TagAndLayersConfigs.Tag.Player) || rayInfo.collider.tag.Equals(TagAndLayersConfigs.Tag.Bird))
            {
                return true;
            }
        }
        return false;
    }


    private void Catch(Transform Player)
    {

    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag.Equals(TagAndLayersConfigs.Tag.Player))
        {
            isfind = false;
        }
    }

}
